<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { apiGet } from '../../utils/api.js'

const router = useRouter()

// 仪表板数据
const dashboardData = ref({
  totalBalance: 0,
  totalPayable: 0,
  overduePayable: 0,
  totalReceivable: 0,
  overdueReceivable: 0,
  monthlyPayment: 0,
  monthlyReceipt: 0
})

// 最近活动数据
const recentActivities = ref([])

// 加载仪表板数据（兼容扁平与包裹结构）
async function loadDashboardData() {
  try {
    const res = await apiGet('/finance/dashboard')
    const payload = (res && typeof res === 'object' && 'data' in res && res.data) ? res.data : res
    if (payload && typeof payload === 'object') {
      dashboardData.value = {
        totalBalance: Number(payload.totalBalance) || 0,
        totalPayable: Number(payload.totalPayable) || 0,
        overduePayable: Number(payload.overduePayable) || 0,
        totalReceivable: Number(payload.totalReceivable) || 0,
        overdueReceivable: Number(payload.overdueReceivable) || 0,
        monthlyPayment: Number(payload.monthlyPayment) || 0,
        monthlyReceipt: Number(payload.monthlyReceipt) || 0
      }
    }
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    // 使用默认数据
    dashboardData.value = {
      totalBalance: 1250000,
      totalPayable: 450000,
      overduePayable: 120000,
      totalReceivable: 680000,
      overdueReceivable: 85000,
      monthlyPayment: 320000,
      monthlyReceipt: 450000
    }
  }
}

// 加载最近活动（基于现有真实功能聚合）
async function loadRecentActivities() {
  try {
    // 并发拉取：手动付款、付款审批(已通过)、订单付款、收款记录
    const [manualPayments, approvedPayments, orderPayments, collectionRecords] = await Promise.all([
      apiGet('/finance/manual-payments').catch(() => ({ items: [] })),
      apiGet('/finance/payment-approvals?status=approved').catch(() => ({ items: [] })),
      apiGet('/finance/order-payments').catch(() => ({ items: [] })),
      apiGet('/finance/collection-records').catch(() => ({ items: [] }))
    ])

    const normalize = (res) => {
      const payload = res && typeof res === 'object' && 'data' in res ? res.data : res
      if (Array.isArray(payload)) return payload
      if (payload && Array.isArray(payload.items)) return payload.items
      if (payload && Array.isArray(payload.list)) return payload.list
      if (payload && Array.isArray(payload.records)) return payload.records
      if (payload && Array.isArray(payload.rows)) return payload.rows
      if (payload && Array.isArray(payload.content)) return payload.content
      return []
    }

    const payments1 = normalize(manualPayments).map((r) => ({
      id: `mp_${r.id}`,
      type: 'payment',
      icon: '💳',
      title: '供应商付款',
      description: `${r.supplierName || '供应商'} 付款 ¥${r.amount || r.totalAmount || 0}`,
      time: r.paymentDate || r.createTime || r.updatedAt || ''
    }))

    const payments2 = normalize(approvedPayments).map((r) => ({
      id: `pa_${r.id}`,
      type: 'approval',
      icon: '✅',
      title: '付款审批通过',
      description: `${r.supplierName || '供应商'} 审批金额 ¥${r.amount || r.totalAmount || 0}`,
      time: r.approvedAt || r.updateTime || r.createTime || ''
    }))

    const payments3 = normalize(orderPayments).map((r) => ({
      id: `op_${r.id}`,
      type: 'payment',
      icon: '🏷️',
      title: '订单付款',
      description: `订单 ${r.orderCode || ''} 付款 ¥${r.amount || r.totalAmount || 0}`,
      time: r.paymentDate || r.createTime || ''
    }))

    const receipts = normalize(collectionRecords).map((r) => ({
      id: `cr_${r.id}`,
      type: 'receipt',
      icon: '💰',
      title: '客户回款',
      description: `${r.customerName || '客户'} 收款 ¥${r.amount || r.totalAmount || 0}`,
      time: r.collectionDate || r.createTime || ''
    }))

    // 合并并按时间倒序，取最近6条
    const all = [...payments1, ...payments2, ...payments3, ...receipts].filter(a => a && (a.title || a.description))
    const parseTime = (t) => new Date(t || 0).getTime() || 0
    recentActivities.value = all.sort((a, b) => parseTime(b.time) - parseTime(a.time)).slice(0, 6)
  } catch (error) {
    console.error('加载最近活动失败:', error)
    recentActivities.value = []
  }
}

// 格式化数字
function formatNumber(num) {
  return new Intl.NumberFormat('zh-CN').format(num || 0)
}

// 导航函数
function navigateToAccounts() {
  router.push('/finance/accounts-payable')
}

function navigateToBills() {
  router.push('/finance/payment-record')
}

function navigateToReports() {
  router.push('/finance/supplier-reconciliation')
}

// 页面加载时获取数据
onMounted(() => {
  loadDashboardData()
  loadRecentActivities()
})
</script>

<template>
  <div class="finance-dashboard">
    <div class="dashboard-header">
      <h1>财务管理</h1>
      <p class="subtitle">财务数据概览与统计分析</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon account-icon">💰</div>
        <div class="stat-content">
          <h3>账户总余额</h3>
          <p class="stat-value">¥{{ formatNumber(dashboardData.totalBalance) }}</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon payable-icon">📤</div>
        <div class="stat-content">
          <h3>应付账款</h3>
          <p class="stat-value">¥{{ formatNumber(dashboardData.totalPayable) }}</p>
          <p class="stat-subtitle">逾期: ¥{{ formatNumber(dashboardData.overduePayable) }}</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon receivable-icon">📥</div>
        <div class="stat-content">
          <h3>应收账款</h3>
          <p class="stat-value">¥{{ formatNumber(dashboardData.totalReceivable) }}</p>
          <p class="stat-subtitle">逾期: ¥{{ formatNumber(dashboardData.overdueReceivable) }}</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon monthly-icon">📊</div>
        <div class="stat-content">
          <h3>本月收支</h3>
          <p class="stat-value">收: ¥{{ formatNumber(dashboardData.monthlyReceipt) }}</p>
          <p class="stat-subtitle">支: ¥{{ formatNumber(dashboardData.monthlyPayment) }}</p>
        </div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <h2>快捷操作</h2>
      <div class="action-buttons">
        <button class="action-btn" @click="router.push('/finance/accounts-payable')">
          <span class="btn-icon">📤</span>
          应付账款
        </button>
        <button class="action-btn" @click="router.push('/finance/accounts-receivable')">
          <span class="btn-icon">📥</span>
          应收账款
        </button>
        <button class="action-btn" @click="router.push('/finance/payment-record')">
          <span class="btn-icon">💳</span>
          付款记录
        </button>
        <button class="action-btn" @click="router.push('/finance/collection-record')">
          <span class="btn-icon">💰</span>
          收款记录
        </button>
        <button class="action-btn" @click="router.push('/finance/order-payment')">
          <span class="btn-icon">🧾</span>
          订单付款
        </button>
        <button class="action-btn" @click="router.push('/finance/order-collection')">
          <span class="btn-icon">📦</span>
          订单回款
        </button>
        <button class="action-btn" @click="router.push('/finance/supplier-reconciliation')">
          <span class="btn-icon">📈</span>
          供应商对账
        </button>
        <button class="action-btn" @click="router.push('/finance/customer-reconciliation')">
          <span class="btn-icon">📊</span>
          客户对账
        </button>
      </div>
    </div>

    <!-- 最近活动 -->
    <div class="recent-activities">
      <h2>最近活动</h2>
      <div class="activity-list">
        <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
          <div class="activity-icon" :class="activity.type">{{ activity.icon }}</div>
          <div class="activity-content">
            <h4>{{ activity.title }}</h4>
            <p>{{ activity.description }}</p>
            <span class="activity-time">{{ activity.time }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.finance-dashboard {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
}

.dashboard-header h1 {
  color: #1f2937;
  margin-bottom: 8px;
}

.subtitle {
  color: #6b7280;
  font-size: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
}

.account-icon { background: #dbeafe; }
.payable-icon { background: #fef3c7; }
.receivable-icon { background: #dcfce7; }
.monthly-icon { background: #f3e8ff; }

.stat-content h3 {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.stat-value {
  margin: 0 0 4px 0;
  color: #111827;
  font-size: 24px;
  font-weight: 700;
}

.stat-subtitle {
  margin: 0;
  color: #6b7280;
  font-size: 12px;
}

.quick-actions {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 30px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.quick-actions h2 {
  margin: 0 0 20px 0;
  color: #1f2937;
}

.action-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  background: #3b82f6;
  color: white;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.action-btn:hover {
  background: #2563eb;
}

.btn-icon {
  font-size: 18px;
}

.recent-activities {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.recent-activities h2 {
  margin: 0 0 20px 0;
  color: #1f2937;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px;
  border-radius: 8px;
  background: #f9fafb;
  transition: background 0.2s;
}

.activity-item:hover {
  background: #f3f4f6;
}

.activity-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-size: 20px;
}

.activity-icon.payment { background: #fef3c7; }
.activity-icon.receipt { background: #dcfce7; }
.activity-icon.approval { background: #dbeafe; }

.activity-content h4 {
  margin: 0 0 4px 0;
  color: #111827;
  font-size: 14px;
  font-weight: 600;
}

.activity-content p {
  margin: 0 0 4px 0;
  color: #6b7280;
  font-size: 13px;
}

.activity-time {
  color: #9ca3af;
  font-size: 12px;
}
</style>


